package com.example.controller;


import com.example.pojo.Car;
import com.example.pojo.Cartype;
import com.example.service.CarService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
@Api
@RequestMapping("/")
public class CarController {
    @Autowired
    private CarService edocEntryService;

    @GetMapping("/")
    public String redirectToEdocList() {
        return "redirect:/list";
    }

    @GetMapping("/add")
    public String toAdd() {
        return "add";
    }

    @PostMapping("/add")
    public String add(Car edocEntry) {
        Integer add = edocEntryService.add(edocEntry);
        if(add>0){
            return "redirect:/list";
        }
        return "add";
    }


    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(required = false) Integer categoryId,
                       @RequestParam(required = false) String name,
                       @RequestParam(defaultValue = "1") Integer startIndex,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        List<Car> list = edocEntryService.list(categoryId,name, startIndex, pageSize).getRecords();
        Long count = edocEntryService.count(categoryId);

        model.addAttribute("list", list);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("startIndex",startIndex);
        model.addAttribute("pageCount",count);
        return "list";
    }

    @GetMapping("/categoryList")
    @ResponseBody
    public List<Cartype> list() {
        return edocEntryService.carType();
    }

    @GetMapping("/selectById")
    public String selectById(Model model, Integer id) {
        Car edocEntry = edocEntryService.getById(id);
        model.addAttribute("ed", edocEntry);
        return "update";
    }

    @PostMapping("/update")
    public String update(Car edocEntry) {
        if(edocEntryService.toUpdate(edocEntry)>0){
            return "redirect:/list";
        }
        return "error";
    }

    @GetMapping("/delete")
    public String del(Integer id) {
        if(edocEntryService.delete(id)>0){
            return "redirect:/list";
        }
        return "error";
    }
}
